package com.ysy.filter;

import com.ysy.context.SecurityContextHolder;
import com.ysy.persimmons.common.constant.SecurityConstants;
import com.ysy.persimmons.common.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.filter.RequestContextFilter;

import java.io.IOException;

public class UserLoginContextFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(UserLoginContextFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String userId = request.getHeader(SecurityConstants.DETAILS_USER_ID);
        if (StringUtils.isBlank(userId)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 存储userID
        SecurityContextHolder.setUserId(userId);
        try {
            filterChain.doFilter(request, response);
        }finally {
            logger.info("User logged in remove");
            SecurityContextHolder.remove();
        }
    }
}
